'use client';

import React, { useState } from 'react';
import { Dialog, DialogContent, DialogTrigger, DialogTitle } from './ui/dialog';
import { Button } from './ui/button';
import { login, register, storeToken } from '../services/authService';
import { LoginRequest, RegisterRequest } from '../types/auth';

// 登录/注册模态框组件
interface LoginRegisterModalProps {
  onLoginSuccess?: () => void;
}

const LoginRegisterModal: React.FC<LoginRegisterModalProps> = ({ onLoginSuccess }) => {
  // 界面状态
  const [mode, setMode] = useState<'login' | 'register'>('login');
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    email: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState({
    email: '',
    username: '',
  });

  // 处理输入变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    setError(null);
    
    // 实时验证字段
    if (mode === 'register') {
      if (name === 'email') {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        setFieldErrors(prev => ({
          ...prev,
          email: value && !emailRegex.test(value) ? '请输入有效的邮箱地址' : ''
        }));
      } else if (name === 'username') {
        setFieldErrors(prev => ({
          ...prev,
          username: value && value.trim().length < 3 ? '用户名至少需要3个字符' : ''
        }));
      }
    }
  };
  
  // 输入框失去焦点时验证
  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    if (mode === 'register') {
      if (name === 'email') {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        setFieldErrors(prev => ({
          ...prev,
          email: value && !emailRegex.test(value) ? '请输入有效的邮箱地址' : ''
        }));
      } else if (name === 'username') {
        setFieldErrors(prev => ({
          ...prev,
          username: value && value.trim().length < 3 ? '用户名至少需要3个字符' : ''
        }));
      }
    }
  };

  // 切换登录/注册模式
  const toggleMode = () => {
    setMode(mode === 'login' ? 'register' : 'login');
    setError(null);
    // 重置字段错误
    setFieldErrors({ email: '', username: '' });
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      let response;
      if (mode === 'login') {
        // 登录请求
        const loginData: LoginRequest = {
          username: formData.email, // 使用邮箱/用户名输入框的值作为登录标识
          password: formData.password
        };
        response = await login(loginData);
      } else {
        // 注册请求
        // 注册时严格验证：用户名和邮箱都必须提供，且邮箱必须符合格式要求
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        
        // 检查是否有字段错误
        let hasError = false;
        const newFieldErrors = { email: '', username: '' };
        
        if (!emailRegex.test(formData.email)) {
          newFieldErrors.email = '请输入有效的邮箱地址';
          hasError = true;
        }
        
        if (!formData.username || formData.username.trim().length < 3) {
          newFieldErrors.username = '用户名至少需要3个字符';
          hasError = true;
        }
        
        setFieldErrors(newFieldErrors);
        
        if (hasError) {
          throw new Error('请检查输入信息');
        }
        
        const registerData: RegisterRequest = {
          username: formData.username,
          password: formData.password,
          email: formData.email
        };
        response = await register(registerData);
        // 注册后自动登录，只传递必要的登录凭证
        const loginData: LoginRequest = {
          username: registerData.username,
          password: registerData.password
        };
        response = await login(loginData);
      }
      
      // token和用户信息已在authService中保存
      
      // 调用成功回调
      if (onLoginSuccess) {
        onLoginSuccess();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button 
          variant="default" 
          size="sm"
          className="bg-gradient-to-r from-blue-400 to-indigo-500 hover:from-blue-500 hover:to-indigo-600 text-white font-medium shadow-md transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5"
        >
          登录/注册
        </Button>
      </DialogTrigger>
      
      <DialogContent className="sm:max-w-md">
        <DialogTitle className="text-xl font-bold mb-4">{mode === 'login' ? '登录' : '注册'}</DialogTitle>
        
        {error && (
          <div className="bg-red-50 text-red-500 p-3 rounded-md mb-4 text-sm">
            {error}
          </div>
        )}
        
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* 注册时需要用户名 */}
          {mode === 'register' && (
            <div>
            <label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
              用户名
            </label>
            <input
              id="username"
              name="username"
              type="text"
              required
              value={formData.username}
              onChange={handleChange}
              onBlur={handleBlur}
              placeholder="请输入用户名"
              className={`w-full px-3 py-2 rounded-md focus:outline-none focus:ring-2 ${fieldErrors.username ? 'border-red-500 focus:ring-red-500' : 'border border-gray-300 focus:ring-blue-500'}`}
            />
            {fieldErrors.username && (
              <p className="text-red-500 text-xs mt-1">{fieldErrors.username}</p>
            )}
          </div>
          )}
          
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
              {mode === 'login' ? '邮箱或用户名' : '邮箱'}
            </label>
            <input
              id="email"
              name="email"
              type={mode === 'login' ? 'text' : 'email'}
              required
              value={formData.email}
              onChange={handleChange}
              onBlur={handleBlur}
              placeholder={mode === 'login' ? '请输入邮箱或用户名' : '请输入邮箱'}
              className={`w-full px-3 py-2 rounded-md focus:outline-none focus:ring-2 ${fieldErrors.email ? 'border-red-500 focus:ring-red-500' : 'border border-gray-300 focus:ring-blue-500'}`}
            />
            {fieldErrors.email && (
              <p className="text-red-500 text-xs mt-1">{fieldErrors.email}</p>
            )}
          </div>
          
          <div>
            <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
              密码
            </label>
            <input
              id="password"
              name="password"
              type="password"
              required
              value={formData.password}
              onChange={handleChange}
              placeholder="请输入密码"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <Button 
            type="submit" 
            disabled={loading} 
            className="w-full bg-gradient-to-r from-blue-400 to-indigo-500 hover:from-blue-500 hover:to-indigo-600 text-white font-medium py-2.5 transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5"
          >
            {loading ? '处理中...' : (mode === 'login' ? '登录' : '注册')}
          </Button>
          
          <div className="text-center text-sm text-gray-600">
            {mode === 'login' ? (
              <>
                还没有账号？ 
                <button 
                  type="button" 
                  onClick={toggleMode}
                  className="text-blue-600 font-medium hover:underline"
                >
                  立即注册
                </button>
              </>
            ) : (
              <>
                已有账号？ 
                <button 
                  type="button" 
                  onClick={toggleMode}
                  className="text-blue-600 font-medium hover:underline"
                >
                  立即登录
                </button>
              </>
            )}
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
};

export default LoginRegisterModal;